package com.JobWebGem.system.controller;

import com.JobWebGem.system.common.BaseResponse;
import com.JobWebGem.system.common.DeleteRequest;
import com.JobWebGem.system.common.ErrorCode;
import com.JobWebGem.system.common.ResultUtils;
import com.JobWebGem.system.exception.BusinessException;
import com.JobWebGem.system.exception.ThrowUtils;
import com.JobWebGem.system.model.dto.job.JobAddRequest;
import com.JobWebGem.system.model.dto.job.JobQueryRequest;
import com.JobWebGem.system.model.dto.job.JobUpdateRequest;
import com.JobWebGem.system.model.entity.Hr;
import com.JobWebGem.system.model.entity.Job;
import com.JobWebGem.system.model.entity.Company;
import com.JobWebGem.system.model.entity.Type;
import com.JobWebGem.system.model.vo.JobVO;
import com.JobWebGem.system.service.HrService;
import com.JobWebGem.system.service.JobService;
import com.JobWebGem.system.service.UserService;
import com.JobWebGem.system.service.CompanyService;
import com.JobWebGem.system.service.TypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 岗位接口
 *
 * @author renli
 */
@RestController
@RequestMapping("/business")
@Slf4j
@Api(tags = "岗位接口")
public class JobController {

    @Resource
    private UserService userService;

    @Resource
    private JobService jobService;

    @Resource
    private HrService hrService;

    @Resource
    private CompanyService companyService;

    @Resource
    private TypeService typeService;

    // region 增删改查

    /**
     * 创建岗位
     *
     * @param jobAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建岗位（仅hr）")
    public BaseResponse<Integer> addBusiness(@RequestBody JobAddRequest jobAddRequest, HttpServletRequest request) {
        if (jobAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Integer id = userService.getLoginUser(request).getId();
        QueryWrapper<Hr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", id);
        Hr hr = hrService.getOne(queryWrapper);

        // 根据typeName查找对应的typeId
        String typeName = jobAddRequest.getTypeName().trim(); // 去除空格
        log.info("正在查找岗位类型（处理前）: {}", jobAddRequest.getTypeName());
        log.info("正在查找岗位类型（处理后）: {}", typeName);

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
        // 使用like而不是eq，这样可以不区分大小写
        typeQueryWrapper.like("typeName", typeName);
        List<Type> types = typeService.list(typeQueryWrapper);
        log.info("查找到的所有匹配岗位类型: {}", types);

        Type type = null;
        if (!types.isEmpty()) {
            // 找到完全匹配的（忽略大小写）
            type = types.stream()
                    .filter(t -> t.getTypeName().equalsIgnoreCase(typeName))
                    .findFirst()
                    .orElse(null);
        }
        log.info("最终选择的岗位类型: {}", type);

        if (type == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "岗位类型不存在");
        }

        Job job = new Job();
        BeanUtils.copyProperties(jobAddRequest, job);
        job.setCompanyId(hr.getCompanyId());
        job.setTypeId(type.getId()); // 设置正确的typeId
        log.info("即将保存的岗位信息: {}", job);
        boolean result = jobService.save(job);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(job.getId());
    }

    /**
     * 删除岗位
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除岗位")
    public BaseResponse<Boolean> deleteBusiness(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        boolean result = jobService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新岗位
     *
     * @param jobUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新岗位")
    public BaseResponse<Boolean> updateHr(@RequestBody JobUpdateRequest jobUpdateRequest, HttpServletRequest request) {
        if (jobUpdateRequest == null || jobUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 查询原有岗位信息
        Job oldJob = jobService.getById(jobUpdateRequest.getId());
        ThrowUtils.throwIf(oldJob == null, ErrorCode.NOT_FOUND_ERROR, "岗位不存在");

        // 只更新不为空的字段
        if (jobUpdateRequest.getJob() != null && !jobUpdateRequest.getJob().trim().isEmpty()) {
            oldJob.setJob(jobUpdateRequest.getJob());
        }
        if (jobUpdateRequest.getTypeName() != null && !jobUpdateRequest.getTypeName().trim().isEmpty()) {
            // 根据typeName查找对应的typeId
            QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
            typeQueryWrapper.eq("typeName", jobUpdateRequest.getTypeName().trim());
            Type type = typeService.getOne(typeQueryWrapper);
            if (type != null) {
                oldJob.setTypeId(type.getId());
            }
        }
        if (jobUpdateRequest.getEducation() != null && !jobUpdateRequest.getEducation().trim().isEmpty()) {
            oldJob.setEducation(jobUpdateRequest.getEducation());
        }
        if (jobUpdateRequest.getExperience() != null && !jobUpdateRequest.getExperience().trim().isEmpty()) {
            oldJob.setExperience(jobUpdateRequest.getExperience());
        }
        if (jobUpdateRequest.getSalary() != null && !jobUpdateRequest.getSalary().trim().isEmpty()) {
            oldJob.setSalary(jobUpdateRequest.getSalary());
        }
        if (jobUpdateRequest.getArea() != null && !jobUpdateRequest.getArea().trim().isEmpty()) {
            oldJob.setArea(jobUpdateRequest.getArea());
        }
        if (jobUpdateRequest.getAddress() != null && !jobUpdateRequest.getAddress().trim().isEmpty()) {
            oldJob.setAddress(jobUpdateRequest.getAddress());
        }
        if (jobUpdateRequest.getDescription() != null && !jobUpdateRequest.getDescription().trim().isEmpty()) {
            oldJob.setDescription(jobUpdateRequest.getDescription());
        }

        // 执行更新
        boolean result = jobService.updateById(oldJob);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(result);
    }

    /**
     * 获取所有岗位
     *
     * @return Page<JobVO>
     */
    @PostMapping("/list/page")
    @ApiOperation("获取所有岗位")
    public BaseResponse<Page<JobVO>> listUserByPage(@RequestBody JobQueryRequest jobQueryRequest) {
        long current = jobQueryRequest.getCurrent() == 0 ? 1 : jobQueryRequest.getCurrent();
        long pageSize = jobQueryRequest.getPageSize() == 0 ? 10 : jobQueryRequest.getPageSize();

        // 1. 获取所有岗位类别，用于后续快速查找
        List<Type> typeList = typeService.listAllTypes();
        log.info("获取到的岗位类别列表: {}", typeList);

        Map<Integer, String> typeMap = new HashMap<>();
        for (Type type : typeList) {
            typeMap.put(type.getId(), type.getTypeName());
        }
        log.info("岗位类别 Map: {}", typeMap);

        Page<Job> paramPage = new Page<>(current, pageSize);
        Page<Job> jobPage = jobService.listPage(paramPage, jobQueryRequest);

        List<JobVO> jobVOList = new ArrayList<JobVO>();

        for (Job job : jobPage.getRecords()) {
            JobVO jobVO = new JobVO();
            BeanUtils.copyProperties(job, jobVO);
            jobVO.setJobId(job.getId());

            if (job.getCompanyId() != null) {
                Company company = companyService.getById(job.getCompanyId());
                if (company != null) {
                    jobVO.setCompanyName(company.getName());
                } else {
                    jobVO.setCompanyName("");
                }
            }

            // 从 Map 中获取类型名称，避免重复查询数据库
            Integer typeId = job.getTypeId();
            if (typeId != null && typeId > 0) { // 确保 typeId 有效
                String typeName = typeMap.get(typeId);
                log.info("岗位 ID: {}, typeId: {}, 获取到的类型名称: {}",
                        job.getId(), typeId, typeName);
                if (typeName != null) {
                    jobVO.setTypeName(typeName);
                } else {
                    // 如果在 Map 中找不到对应的类型名称，尝试直接从数据库查询
                    Type type = typeService.getById(typeId);
                    if (type != null) {
                        jobVO.setTypeName(type.getTypeName());
                    } else {
                        jobVO.setTypeName("未分类"); // 设置默认值
                    }
                }
            } else {
                jobVO.setTypeName("未分类"); // typeId 无效时设置默认值
            }

            jobVOList.add(jobVO);
        }

        Page<JobVO> resultPage = new Page<JobVO>();
        resultPage.setCurrent(jobPage.getCurrent());
        resultPage.setSize(jobPage.getSize());
        resultPage.setTotal(jobPage.getTotal());
        resultPage.setRecords(jobVOList);

        return ResultUtils.success(resultPage);
    }

    // endregion
}
